/**
 * Created by neu on 2015/1/13.
 */

function getParameterFromUrl(name)
{
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)","i");

	var url = window.location.href;
	var paramString;
	if(url.indexOf("#")){
		if(url.indexOf("#")>=url.indexOf("?")){
			paramString = url.slice(url.indexOf("?")+1,url.indexOf("#"));
		}else{
			paramString = url.slice(url.indexOf("?")+1,url.length);
		}
	}else{
		paramString = window.location.search.substring(1);
	}
	var r = paramString.match(reg);
	if (r != null)
		return unescape(r[2]);
	return null;
}



var domain = getParameterFromUrl("env") || "qa.yunchelife.com";
var snsDomain =getParameterFromUrl("SnsEnv");
var useDummy = false;
var isLocalDebug = false;
var useLog = false;
var userType = {
	undefined:0,
	doctor:1,
	consultant:2
};

function getStorageValue(key)
{
	var data = getParameterFromUrl(key);
	if(data==''||data==null)
		data=localStorage.getItem(key);
	else
		localStorage.setItem(key,data);
	return data;
}

function getSnsEnv(){
	return localStorage.getItem('snsEnv');
}

function getSnsApiKey(){
	return localStorage.getItem('snsApiKey');
}

function getSnsToken(){
	return localStorage.getItem('snsToken');
}

function getAuthToken()
{
	return window.localStorage.getItem('Token');
};

function getUserType(){
	return localStorage.getItem('UserType');//根据对应的key获取对应的的value
};

function setAuthToken(token)
{
	window.localStorage.setItem('Token',token);
};

function setSnsToken(token){
	localStorage.setItem('snsToken', token);
}

function setUserType(userType){
	localStorage.setItem('UserType',userType);
};

function prompt (info){
	if(isLocalDebug){
		alert(info);
	}
}

function getIsFirst(){
	return localStorage.getItem('isFirst');
}

function setIsFirst(isFirst){
	localStorage.setItem('isFirst', isFirst);
}

function setExitSNSSiteUrl(url){
	localStorage.setItem('exitSNSUrl', url);//添加,编辑localStorage(本地存储(键，值))的内容
	localStorage.setItem('snsKey', "");
}

var glbFooterType = {'main':'main', 'friendDetail':'friend_detail', 'myInfoNext':'info_next'};

var conste =
	[
		{name:'水瓶座',id:0},
		{name:'双鱼座',id:1},
		{name:'白羊座',id:2},
		{name:'金牛座',id:3},
		{name:'双子座',id:4},
		{name:'巨蟹座',id:5},
		{name:'狮子座',id:6},
		{name:'处女座',id:7},
		{name:'天秤座',id:8},
		{name:'天蝎座',id:9},
		{name:'射手座',id:10},
		{name:'魔蝎座',id:11}
	];

var education = [
	{name:'本科', id: 0},
	{name:'硕士', id: 1},
	{name:'博士', id: 2}
];
var gender =
	[
		{gen:'男', id: 1},
		{gen:'女', id: 2}

	];

var app = angular.module('app', ['ngRoute', 'ngAnimate', 'ngCookies', 'localization', 'ui.bootstrap']).config(
	["$routeProvider", function($routeProvider){
		$routeProvider.
			when('/', {templateUrl: 'views/consultant/index.html', controller: 'ConsultantHomeController'}).
			when('/myPersonInfo', {templateUrl: 'views/myPersonInfo.html', controller: 'MyPersonInfoController'}).
			when('/consultant/index', {templateUrl: 'views/consultant/index.html', controller: 'ConsultantHomeController'}).
			when('/myInfoDetails/myInfo', {templateUrl: 'views/myInfo.html', controller: 'MyInfoController'}).
			when('/myPersonInfo/myState', {templateUrl: 'views/myState.html', controller: 'MyStateInfoController'}).
			when('/myPersonInfo/myCollection', {templateUrl: 'views/myCollection.html', controller: 'MyCollectionInfoController'}).
			when('/myPersonInfo/myMail', {templateUrl: 'views/myMail.html', controller: 'MyMailInfoController'}).
			when('/myPersonInfo/myAbout', {templateUrl: 'views/myAbout.html', controller: 'MyAboutInfoController'}).
			when('/friends', {templateUrl: 'views/myFriends.html', controller: 'MyFriendsController'}).
			when('/search', {templateUrl: 'views/search.html', controller: 'SearchController'}).
			when('/detailsInfo', {templateUrl: 'views/detailsInfo.html', controller: 'DetailsInfoController'}).
			when('/topicDetails', {templateUrl: 'views/topicDetails.html', controller: 'TopicDetailsController'}).
			when('/myPersonInfo/myInfo/description',{templateUrl : 'views/tmpl_description.html', controller: 'DescriptionController'}).
			when('/newFriends', {templateUrl:'views/newFriends.html', controller: 'NewFriendsController'}).
			when('/myPersonInfo/myInfo/description/attestation', {templateUrl:'views/tmpl_attestation.html', controller: 'AttestationController'}).
			when('/myPersonInfo/myInfo/description/attestation/profile', {templateUrl:'views/tmpl_profile.html', controller:'ProfileController'}).
			when('/myPersonInfo/myInfo/description/attestation/profile/examineState', {templateUrl: 'views/tmpl_examineState.html', controller:'ExamineStateController'}).
			when('/myPersonInfo/pay', {templateUrl: 'views/tmpl_pay.html', controller: 'PayController'}).
			when('/becomeVIP', {templateUrl: 'views/become_vip.html', controller: 'BecomeVipController'}).
			when('/myPersonInfo/myInfoDetails', {templateUrl: 'views/myInfo_details.html', controller: 'MyInfoDetailsController'}).
			when('/user/login', {templateUrl: 'views/login.html', controller: 'UserLoginController'}).
			when('/user/register', {templateUrl: 'views/register.html', controller: 'UserRegisterController'}).
			when('/user/findPassWord', {templateUrl: 'views/find_password.html', controller: 'FindPassWordController'}).
			when('/user/register/complete', {templateUrl:'views/complete.html', controller: 'CompleteController'}).
			when('/alreadyVIP', {templateUrl:'views/already_VIP.html', controller:'AlreadyVIPController'}).
			when('/loadingHead', {templateUrl:'views/tmp_loading.html', controller: 'LoadingHeadController'}).
			when('/myPersonInfo/integral', {templateUrl: 'views/tmp_integral.html', controller: 'IntegralController'}).
			when('/myPersonInfo/integral/shareFriends', {templateUrl:'views/share_friends.html', controller:'ShareFriendsController'}).
			when('/changePassword', {templateUrl: 'views/change_password.html', controller: 'changePasswordController'}).
			when('/playIntegral', {templateUrl: 'views/play_integral.html', controller: 'PlayIntegralController'}).
			when('/promptRegister', {templateUrl: 'views/prompt_register.html', controller: 'PromptRegisterController'}).
			when('/promptExamine', {templateUrl: 'views/prompt_examine.html', controller: 'PromptExamineController'}).
			when('/promptFeedback', {templateUrl: 'views/prompt_feedback.html', controller: 'PromptFeedbackController'}).
			when('/integralPrompt', {templateUrl: 'views/integral_prompt.html', controller: 'IntegralPromptController'}).//积分不足提示
			when('/myPersonInfo/myAbout/about', {templateUrl: 'views/about.html', controller: 'AboutController'}).
			when('/myPersonInfo/myAbout/agreement', {templateUrl: 'views/agreement.html', controller: 'AgreementController'}).
			when('/searchFriends', {templateUrl: 'views/search_friends.html', controller: 'searchFriendsController'}).
			when('/memberno', {templateUrl: 'views/search_memberno.html', controller: 'MembernoController'}).
			when('/playScore', {templateUrl: 'views/tmp_playScore.html', controller: 'PlayScoreController'}).
			//when('/successIntegral', {templateUrl: 'views/success_integral.html', controller: 'SuccessIntegralController'}).
			when('/SuccessVIP', {templateUrl: 'views/success_VIP.html', controller: 'SuccessVIPController'}).
			when('/collect', {templateUrl: 'views/collect.html', controller: 'CollectController'}).
			when('/searchCountFull', {templateUrl: 'views/searchCount_full.html', controller: 'SearchCountFullController'}).
			when('/SuccessPayIntegral', {templateUrl: 'views/success_payIntegral.html', controller: 'SuccessPayIntegralController'}).
			when('/PayFails', {templateUrl: 'views/pay_fails.html', controller: 'PayFailsVIPController'}).
			when('/shareSuccess', {templateUrl: 'views/share_success.html', controller: 'ShareSuccessController'}).
			when('/PayFailsIntegral', {templateUrl: 'views/pay_failsIntegral.html', controller: 'PayFailsIntegralController'}).

			// for sign up
			otherwise({redirectTo: '/'});
	}]
).config(function($sceProvider){
		$sceProvider.enabled(false);
	});


var browser={
	versions:function(){
		var u = navigator.userAgent, app = navigator.appVersion;
		return {
			trident: u.indexOf('Trident') > -1, //IE
			presto: u.indexOf('Presto') > -1, //opera
			webKit: u.indexOf('AppleWebKit') > -1, //webkit
			gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //firefox
			mobile: !!u.match(/AppleWebKit.*Mobile.*/), //mobile
			ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios
			android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android or uc
			iPhone: u.indexOf('iPhone') > -1 , //iPhone QQHD
			iPad: u.indexOf('iPad') > -1, //iPad
			webApp: u.indexOf('Safari') == -1
		};
	}(),
	language:(navigator.browserLanguage || navigator.language).toLowerCase()
}
function iOS7() {
	if (/iP(hone|od|ad)/.test(navigator.platform)) {
		var v = (navigator.appVersion).match(/OS (\d+)_(\d+)_?(\d+)?/);
		var vers = [parseInt(v[1], 10), parseInt(v[2], 10), parseInt(v[3] || 0, 10)];
		if(vers[0] >=7)
			return true;
		return false;
	}
	return false;
}

//for ios
var connectWebViewJavascriptBridge = function(callback){
	if (window.WebViewJavascriptBridge) {
		callback(WebViewJavascriptBridge)
	} else {
		document.addEventListener('WebViewJavascriptBridgeReady', function() {
			callback(WebViewJavascriptBridge)
		}, false)
	}
};
if(browser.versions.ios){
	connectWebViewJavascriptBridge(function(bridge){
		bridge.init(function(message, responseCallback) {
			var data = { 'Javascript Responds':'Wee!' };
			console.log('JS responding with', data)
			responseCallback(data)
		});
		bridge.registerHandler("uploadImageCallback", function(data, responseCallback) {
			console.log("uploadImageCallback", data)

			var evt = document.createEvent("Events");
			evt.data = data;
			evt.initEvent("FILE_UPLOADED_EVENT", false, true);

			document.dispatchEvent(evt);

			var responseData = { 'Javascript Says':'got images!' }
			responseCallback(responseData)
		});
		bridge.registerHandler("uploadImageCancelCallback", function(data, responseCallback) {
			console.log("uploadImageCancelCallback", data)

			var evt = document.createEvent("Events");
			evt.data = data;
			evt.initEvent("FILE_UPLOAD_CANCEL_EVENT", false, true);

			document.dispatchEvent(evt);

			var responseData = { 'Javascript Says':'cancel upload!' }
			responseCallback(responseData)
		});
		bridge.registerHandler("getUnReadCallback", function(data, responseCallback) {
			console.log("getUnReadCallback", data)

			var evt = document.createEvent("Events");
			evt.data = data;
			evt.initEvent("GET_UNREAD_CALLBACK", false, true);

			document.dispatchEvent(evt);

			var responseData = { 'Javascript Says':'got unread message counts!' }
			responseCallback(responseData)
		});
		bridge.registerHandler("shareInfoCallback", function(data, responseCallback) {
			console.log("shareInfoCallback", data)

			var evt = document.createEvent("Events");
			evt.data = data;
			evt.initEvent("SHARE_INFO_CALLBACK", false, true);

			document.dispatchEvent(evt);

			var responseData = { 'Javascript Says':'got share info result!' }
			responseCallback(responseData)
		});
		bridge.registerHandler("handlePushMsgCallback", function(data, responseCallback) {
			console.log("handlePushMsgCallback", data)

			var evt = document.createEvent("Events");
			evt.data = data;
			evt.initEvent("HANDLE_PUSH_CALLBACK", false, true);

			document.dispatchEvent(evt);

			var responseData = { 'Javascript Says':'got handle push result!' }
			responseCallback(responseData)
		});
		bridge.registerHandler("handleHXPushMsgCallback", function(data, responseCallback) {
			console.log("handleHXPushMsgCallback", data)

			var evt = document.createEvent("Events");
			evt.data = data;
			evt.initEvent("HANDLE_HXPUSH_CALLBACK", false, true);

			document.dispatchEvent(evt);

			var responseData = { 'Javascript Says':'got handle hxPush result!' }
			responseCallback(responseData)
		});
		bridge.registerHandler("getAppVersionCallback", function(data, responseCallback) {
			console.log("getAppVersionCallback", data)

			var evt = document.createEvent("Events");
			evt.data = data;
			evt.initEvent("GET_VERSION_CALLBACK", false, true);

			document.dispatchEvent(evt);

			var responseData = { 'Javascript Says':'got get version result!' }
			responseCallback(responseData)
		});

	});
}

// for android
if(browser.versions.android && jsb && jsb.addJavascriptMethod){

	//Log.log("android: " , browser.versions)
	jsb.addJavascriptMethod('uploadImageCallback', function(params){
		Log.log("called by native: uploadImageCallback=====")
		var evt = document.createEvent("Events");
		evt.data = params;
		evt.initEvent("FILE_UPLOADED_EVENT", false, true);

		document.dispatchEvent(evt);
		Log.log("FILE_UPLOADED_EVENT dispatched")
		return {'text': 'uploadImageCallback ok'};
	});

	jsb.addJavascriptMethod('uploadImageCancelCallback', function(params){
		Log.log("called by native: uploadImageCancelCallback=====")
		var evt = document.createEvent("Events");
		evt.data = params;
		evt.initEvent("FILE_UPLOAD_CANCEL_EVENT", false, true);

		document.dispatchEvent(evt);

		return {'text': 'uploadImageCancelCallback ok'};
	});

	jsb.addJavascriptMethod('backCallback', function(params){
		Log.log("called by native: backCallback=====")
		var evt = document.createEvent("Events");
		evt.data = params;
		evt.initEvent("NAVIGATION_BACK_EVENT", false, true);

		document.dispatchEvent(evt);

		return {'text': 'backCallback ok'};
	});

	jsb.addJavascriptMethod('getUnReadCallback', function(params){
		Log.log("called by native: uploadImageCancelCallback=====")
		var evt = document.createEvent("Events");
		evt.data = params.hxUnReadInfo;
		evt.initEvent("GET_UNREAD_CALLBACK", false, true);

		document.dispatchEvent(evt);

		return {'text': 'got getUnReadCallback message ok'};
	});

	jsb.addJavascriptMethod('shareInfoCallback', function(params){
		Log.log("called by native: shareInfoCallback=====")
		var evt = document.createEvent("Events");
		evt.data = params;
		evt.initEvent("SHARE_INFO_CALLBACK", false, true);

		document.dispatchEvent(evt);

		return {'text': 'got shareInfoCallback message ok'};
	});

	jsb.addJavascriptMethod('getAppVersionCallback', function(params){
		Log.log("called by native: getAppVersionCallback=====")

		var evt = document.createEvent("Events");
		evt.data = params;
		evt.initEvent("GET_VERSION_CALLBACK", false, true);

		document.dispatchEvent(evt);

		return {'text': 'got getAppVersionCallback message ok'};
	});

	jsb.addJavascriptMethod('handlePushMsgCallback', function(params){
		Log.log("called by native: handlePushMsgCallback=====")

		var evt = document.createEvent("Events");
		evt.data = params;
		evt.initEvent("HANDLE_PUSH_CALLBACK", false, true);

		document.dispatchEvent(evt);

		return {'text': 'got handlePushMsgCallback message ok'};
	});

	jsb.addJavascriptMethod('handleHXPushMsgCallback', function(params){
		Log.log("called by native: handleHXPushMsgCallback=====")

		var evt = document.createEvent("Events");
		evt.data = params;
		evt.initEvent("HANDLE_HXPUSH_CALLBACK", false, true);

		document.dispatchEvent(evt);

		return {'text': 'got handleHXPushMsgCallback message ok'};
	});
}


function getIdCardInfo(cardNo) {
	if(!cardNo)
		return false;
	var info = {
		isTrue : false,
		year : null,
		month : null,
		day : null,
		isMale : false,
		isFemale : false
	};
	if (!cardNo && 15 != cardNo.length && 18 != cardNo.length) {
		info.isTrue = false;
		return info;
	}
	if (15 == cardNo.length) {
		var year = cardNo.substring(6, 8);
		var month = cardNo.substring(8, 10);
		var day = cardNo.substring(10, 12);
		var p = cardNo.substring(14, 15); //
		var birthday = new Date(year, parseFloat(month) - 1,
			parseFloat(day));
		if (birthday.getYear() != parseFloat(year)
			|| birthday.getMonth() != parseFloat(month) - 1
			|| birthday.getDate() != parseFloat(day)) {
			info.isTrue = false;
		} else {
			info.isTrue = true;
			info.year = birthday.getFullYear();
			info.month = birthday.getMonth() + 1;
			info.day = birthday.getDate();
			if (p % 2 == 0) {
				info.isFemale = true;
				info.isMale = false;
			} else {
				info.isFemale = false;
				info.isMale = true
			}
		}
		return info;
	}
	if (18 == cardNo.length) {
		var year = cardNo.substring(6, 10);
		var month = cardNo.substring(10, 12);
		var day = cardNo.substring(12, 14);
		var p = cardNo.substring(14, 17)
		var birthday = new Date(year, parseFloat(month) - 1,
			parseFloat(day));
		if (birthday.getFullYear() != parseFloat(year)
			|| birthday.getMonth() != parseFloat(month) - 1
			|| birthday.getDate() != parseFloat(day)) {
			info.isTrue = false;
			return info;
		}
		var Wi = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1 ];
		var Y = [ 1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2 ];
		var sum = 0;
		var _cardNo = cardNo.split("");
		if (_cardNo[17].toLowerCase() == 'x') {
			_cardNo[17] = 10;
		}
		for ( var i = 0; i < 17; i++) {
			sum += Wi[i] * _cardNo[i];
		}
		var i = sum % 11;
		if (_cardNo[17] != Y[i]) {
			return info.isTrue = false;
		}

		info.isTrue = true;
		info.year = birthday.getFullYear();
		info.month = birthday.getMonth() + 1;
		info.day = birthday.getDate();
		if (p % 2 == 0) {
			info.isFemale = true;
			info.isMale = false;
		} else {
			info.isFemale = false;
			info.isMale = true
		}
		return info;
	}
	return info;
}

function internalLogin(authToken, snsToken){
	var authToken = { authToken: authToken, snsToken: snsToken};
	if (browser.versions.ios) {
		Log.log("try to call ios native to login");
		if (window.WebViewJavascriptBridge) {
			WebViewJavascriptBridge.callHandler('login', authToken, function (response) {
				Log.log("call native to login");
			});
		}
	}else if (browser.versions.android) {
		Log.log("try to call android native to login");
		jsb.require('login', authToken, function (response) {
			Log.log("call native to login");
		});
	}
}

function modalMessage ($modal, message){
	var modalInstance = $modal.open({
		templateUrl: 'views/tmpl_modal_alert.html',
		controller: ModalAlertCtrl,
		size: 'sm',
		resolve: {
			alertObj: function () {
				return {message: message};
			}
		}
	});
}
//环信登录
function hxLogin (hxUserName, hxPassWord){
	var params = {hxUserName: hxUserName, hxPassWord: hxPassWord};
	/*alert(JSON.stringify(params));*/
	if (browser.versions.ios) {
		Log.log("try to call ios native to add image");
		if (window.WebViewJavascriptBridge) {
			WebViewJavascriptBridge.callHandler('hxLogin', params, function (response) {
				Log.log("call native to hxLogin");
			});
		}
	} else if (browser.versions.android) {
		Log.log("try to call android native to add image");
		jsb.require('hxLogin', params, function (response) {
			Log.log("call native to hxLogin");
		});

	}
}

//环信聊天
function hxChat (fromUserId, toUserId){
	var params = {fromUserId: fromUserId, toUserId: toUserId};
	if (browser.versions.ios) {
		Log.log("try to call ios native to add image");
		if (window.WebViewJavascriptBridge) {
			WebViewJavascriptBridge.callHandler('hxChat', params, function (response) {
				Log.log("call native to upload image");
			});
		}
	} else if (browser.versions.android) {
		Log.log("try to call android native to add image");
		jsb.require('hxChat', params, function (response) {
			Log.log("call native to upload image");
		});

	}
}
//环信读消息
function hxGetUnRead(hxUserNames){
	var params = {hxUserNames: hxUserNames};
	if (browser.versions.ios) {
		Log.log("try to call ios native to add image");
		if (window.WebViewJavascriptBridge) {
			WebViewJavascriptBridge.callHandler('hxGetUnRead', params, function (response) {
				Log.log("call native to upload image");
			});
		}
	} else if (browser.versions.android) {
		Log.log("try to call android native to add image");
		jsb.require('hxGetUnRead', params, function (response) {
			Log.log("call native to upload image");
		});

	}
}
//朋友分享
function shareInfo(option){
	var params = {url: 'http://www.fashionsingles.org/', title: 'FS高端交友', description: '快来一起加入FashionSingles全认证高端实名温暖家园，认识几个值得认识的朋友！', image: 'http://www.fashionsingles.org/images/fs.png', option: option};
	if (browser.versions.ios) {
		Log.log("try to call ios native to share info");
		if (window.WebViewJavascriptBridge) {
			WebViewJavascriptBridge.callHandler('shareInfo', params, function (response) {
				Log.log("call native to share info");
			});
		}
	} else if (browser.versions.android) {
		Log.log("try to call android native to share info");
		jsb.require('shareInfo', params, function (response) {
			Log.log("call native to share info");
		});

	}
}

//获取版本号
function getAppVersion(){
	if (browser.versions.ios) {
		Log.log("try to call ios native to add image");
		if (window.WebViewJavascriptBridge) {
			WebViewJavascriptBridge.callHandler('getAppVersion', function (response) {
				Log.log("call native to upload image");
			});
		}
	} else if (browser.versions.android) {
		Log.log("try to call android native to add image");
		jsb.require('getAppVersion', {'msg': "logo"}, function (response) {
			Log.log("call native to upload image");
		});

	}
}

